"use strict";

/*http://toddmotto.com/a-comprehensive-dive-into-nodelists-arrays-converting-nodelists-and-understanding-the-dom/*/

var app = angular.module("App", ["ngRoute", "ngSanitize", "ngMaterial", "ngAnimate", "ui.bootstrap"]);

app.run(["$rootScope", "$location", "$window", "$templateCache", "$token", function ($rootScope, $location, $window, $templateCache, $token) {

    //gestion du cache de html5
    window.applicationCache.addEventListener("updateready", function (e) {
        if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
            $templateCache.removeAll();
            window.applicationCache.swapCache();
            window.applicationCache.update();
            window.location.reload();
        }
    }, false);

    $rootScope.$on("$routeChangeStart", function (event, next, current) {
        $token.get().then(function () {
            $rootScope.previousRoute = current;
        }, function () {
            $location.path("/login");
        });
    });
} ]);

app.config(["$routeProvider", "$locationProvider", function ($routeProvider, $locationProvider) {
    $locationProvider.html5Mode = true;
    $routeProvider.
        when("/", {
            templateUrl: "/pro/partials/app.html",
            controller: "AppCtrl"
        }).
        when("/login", {
            templateUrl: "/app/partials/login.html",
            controller: "LoginCtrl"
        }).
        when("/editor/:id/:archive", {
            templateUrl: "/pro/partials/editor.html",
            controller: "EditorCtrl"
        }).
        when("/editor/:id", {
            templateUrl: "/pro/partials/editor.html",
            controller: "EditorCtrl"
        }).
        when("/editor", {
            templateUrl: "/pro/partials/editor.html",
            controller: "EditorCtrl"
        }).
        when("/subscriptions", {
            templateUrl: "/pro/partials/subscriptions.html",
            controller: "ShopSubscriptionsCtrl"
        }).
        when("/account", {
            templateUrl: "/pro/partials/shopAccount.html",
            controller: "ShopAccountCtrl"
        }).
        when("/alert/:id/:archive", {
            templateUrl: "/pro/partials/alert.html",
            controller: "AlertCtrl"
        }).
        when("/alert/:id", {
            templateUrl: "/pro/partials/alert.html",
            controller: "AlertCtrl"
        }).
        when("/shop/:login", {
            templateUrl: "/pro/partials/shop.html",
            controller: "ShopCtrl"
        }).
        otherwise({
            redirectTo: '/'
        });
} ]);

app.controller("AppCtrl", ["$scope", "$rootScope", "$mdSidenav", "appShopAccount", function ($scope, $rootScope, $mdSidenav, appShopAccount) {
    //if(!$rootScope.previousRoute) $scope.viewClass = "app animation-first";
    $scope.viewClass = "app";

    $scope.selectedIndex = 0;

    $scope.next = function () {
        $scope.selectedIndex = Math.min($scope.selectedIndex + 1, 2);
    };

    $scope.previous = function () {
        $scope.selectedIndex = Math.max($scope.selectedIndex - 1, 0);
    };

    $scope.account = appShopAccount;
    $scope.account.init()

    $scope.openMenu = function () {
        $mdSidenav('left').toggle();
    };
} ]);

app.controller("LoginCtrl", ["$scope", "connectPro", "appShopAccount", function ($scope, connectPro, appShopAccount) {
    $scope.pageClass = "login";

    $scope.model = {
        login: "",
        password: ""
    };

    $scope.validate = function () {
        return connectPro.connect($scope.model);
    };
} ]);

app.controller("EditorCtrl", ["$scope", "$rootScope", "$route", "$window", "$mdSidenav", "appShopAccount", "connectPro", "appAlert", "appAlertArchives", "appAlertCreator", "$mdBottomSheet", function ($scope, $rootScope, $route, $window, $mdSidenav, appShopAccount, connectPro, appAlert, appAlertArchives, appAlertCreator, $mdBottomSheet) {
    $scope.pageClass = "editor";

    var alertId = $route.current.params.id;
    var archive = $route.current.params.archive;

    if(alertId) {
        if(archive) $scope.alert = appAlertArchives.get(alertId);
        else $scope.alert = appAlert.get(alertId);
        $scope.alert.init();
    }
    else $scope.alert = appAlertCreator;

    $scope.account = appShopAccount;
    $scope.account.init();

    $scope.openBottomSheet = function (event, index) {
        var target = angular.element(event.target);
        var textarea = target.parent().parent().find('textarea')[0];
        var model;

        if(index == null) model = $scope.alert.data;
        else model = $scope.alert.data.articles[index];

        $mdBottomSheet.show({
            templateUrl: '/pro/partials/bottomsheet/editor.html',
            controller: 'BottomSheetEditorCtrl',
        }).then(function(data){
            model.content = model.content || "";
            var preffix = model.content.substr(0, textarea.selectionStart);
            if (preffix.length > 0 && preffix[preffix.length - 1] != " ") preffix += " ";
            var suffix = model.content.substr(textarea.selectionEnd) || " ";
            model.content = preffix + data + suffix;
        });
    };

    $scope.back = function () {
        $window.history.back();
    };

    $scope.openMenu = function () {
        $mdSidenav('left').toggle();
    };

} ]);

app.controller("AliveCtrl", ["$scope", "appShopAlive", "appShopAccount", function ($scope, appShopAlive, appShopAccount) {
    $scope.pageClass = "alive";

    $scope.account = appShopAccount;
    $scope.account.init();

    $scope.list = appShopAlive;
    $scope.list.init();

} ]);


app.controller("NewsCtrl", ["$scope", "appShopNews", "appShopAccount", function ($scope, appShopNews, appShopAccount) {
    $scope.pageClass = "news";

    $scope.account = appShopAccount;
    $scope.account.init();

    $scope.list = appShopNews;
    $scope.list.init();    

} ]);

app.controller("ArchivesCtrl", ["$scope", "appShopArchives", "appShopAccount", function ($scope, appShopArchives, appShopAccount) {
    $scope.pageClass = "archive";

    $scope.account = appShopAccount;
    $scope.account.init();

    $scope.list = appShopArchives;
    $scope.list.init();

} ]);

app.controller("ShopSubscriptionsCtrl", ["$window", "$scope", "$mdSidenav", "appShopSubscription", "appShopNews", "appShopAccount", function ($window, $scope, $mdSidenav, appShopSubscription, appShopNews, appShopAccount) {
    
    $scope.viewClass = "subscriptions";

    $scope.account = appShopAccount;
    $scope.account.init();

    $scope.list = appShopSubscription;
    $scope.list.init();

    $scope.back = function(){
        $window.history.back();
    };

    $scope.openMenu = function () {
        $mdSidenav('left').toggle();
    };
} ]);

app.controller("AlertCtrl", ["$route", "$mdSidenav","$scope", "$window", "appAlert", "appAlertArchives", "appShopAccount", function ($route, $mdSidenav, $scope, $window, appAlert, appAlertArchives, appShopAccount) {
    $scope.viewClass = "alert";

    var alertId = $route.current.params.id;
    var archive = $route.current.params.archive;

    $scope.account = appShopAccount;
    $scope.account.init();
    
    if(archive) {
        $scope.alert = appAlertArchives.get(alertId);
        $scope.alert.editorSuffix = "/archive";
    }
    else $scope.alert = appAlert.get(alertId);
    $scope.alert.init();

    $scope.back = function(){
        $window.history.back();
    };

    $scope.openMenu = function () {
        $mdSidenav('left').toggle();
    };

} ]);

app.controller("ShopCtrl", ["$scope", "$mdSidenav", "$route", "$window", "appShop", "appShopAlerts", "appShopAccount", function ($scope, $mdSidenav, $route, $window, appShop, appShopAlerts, appShopAccount) {
    $scope.viewClass = "shop";

    var login = $route.current.params.login;

    $scope.account = appShopAccount;
    $scope.account.init();

    $scope.shop = appShop.get(login);
    $scope.shop.init();

    $scope.shopAlerts = appShopAlerts.get(login);
    $scope.shopAlerts.init();

    $scope.back = function () {
        $window.history.back();
    };

    $scope.openMenu = function () {
        $mdSidenav('left').toggle();
    };
} ]);

app.controller("ShopAccountCtrl", ["$http", "$window", "$scope", "$mdSidenav", "googleGeocode", "appShopAccount", "$mdBottomSheet", function ($http, $window, $scope, $mdSidenav, googleGeocode, appShopAccount, $mdBottomSheet) {
    $scope.viewClass = "account";

    $scope.account = appShopAccount;
    $scope.account.init().then(function(){
        $scope.locationText = $scope.account.data.location.address;
    });

    $scope.$watch("category", function(newValue, oldValue){
        if(!newValue) return;
        $scope.account.data.categories.push(newValue);
    });

    $scope.removeCategory = function (index) {
        $scope.account.data.categories.splice(index, 1);
    };

    $scope.getLocation = function (val) {
        return googleGeocode.getLocations(val);
    };

    /*
    $scope.selectEmployee = function () {
        //console.log($scope.employee);
        $scope.account.data.users.employees.push({ _id: $scope.employee._id, login: $scope.employee.login });
        $scope.employee = "";
    };

    $scope.removeEmployee = function (index) {
        $scope.account.data.users.employees.splice(index, 1);
    };
    */

    $scope.openBottomSheet = function (event) {
        var target = angular.element(event.target);
        var textarea = target.parent().parent().find('textarea')[0];
        var model = $scope.account.data.description;

        $mdBottomSheet.show({
            templateUrl: '/pro/partials/bottomsheet/editor.html',
            controller: 'BottomSheetEditorCtrl',
        }).then(function(data){
            var preffix = model.content.substr(0, textarea.selectionStart);
            if (preffix.length > 0 && preffix[preffix.length - 1] != " ") preffix += " ";
            var suffix = model.content.substr(textarea.selectionEnd) || " ";
            model.content = preffix + data + suffix;
        });
    };

    $scope.back = function () {
        $window.history.back();
    };

    $scope.openMenu = function () {
        $mdSidenav('left').toggle();
    };

} ]);

